package threadSynchronization;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: WanqingLiu
 * @Date: 2023/02/04/10:18
 * 测试Lock锁
 */
public class TestLock {

    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }

}

class TestLock2 implements Runnable {
    private static int tikectNum = 100; // 多线程共享的 num

    // 定义 lock 锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (tikectNum <= 0) {
                    System.out.println("票卖完了~~~");
                    break;
                }
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("窗口 " + Thread.currentThread().getName() + " 售出了一张票，还剩的票数为" + (--tikectNum));
            } finally {
                lock.unlock();
            }
        }
    }
}
